//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package widget_store_api_serv

import (
	"context"

	"atomgit.com/openlinksaas/api-server/dao/widget_dao"
	"atomgit.com/openlinksaas/proto-gen-go.git/widget_store_api"
)

type WidgetStoreApiImpl struct {
	widget_store_api.UnimplementedWidgetStoreApiServer
}

func (apiImpl *WidgetStoreApiImpl) ListWidget(ctx context.Context, req *widget_store_api.ListWidgetRequest) (*widget_store_api.ListWidgetResponse, error) {
	widgetItemList, err := widget_dao.WidgetDao.List(ctx)
	if err != nil {
		return nil, err
	}
	widgetList := []*widget_store_api.WidgetInfo{}
	for _, widgetItem := range widgetItemList {
		widgetList = append(widgetList, widgetItem.ToWidgetInfo())
	}
	return &widget_store_api.ListWidgetResponse{
		Code:       widget_store_api.ListWidgetResponse_CODE_OK,
		WidgetList: widgetList,
	}, nil
}

func (apiImpl *WidgetStoreApiImpl) GetWidget(ctx context.Context, req *widget_store_api.GetWidgetRequest) (*widget_store_api.GetWidgetResponse, error) {
	widgetItem, err := widget_dao.WidgetDao.Get(ctx, req.WidgetId)
	if err != nil {
		return &widget_store_api.GetWidgetResponse{
			Code:   widget_store_api.GetWidgetResponse_CODE_NO_WIDGET,
			ErrMsg: "插件不存在",
			Widget: &widget_store_api.WidgetInfo{
				ExtensionList: []string{},
				FileList:      []string{},
			},
		}, nil
	}
	return &widget_store_api.GetWidgetResponse{
		Code:   widget_store_api.GetWidgetResponse_CODE_OK,
		Widget: widgetItem.ToWidgetInfo(),
	}, nil
}
